package com.ewhl.mark.meijialian;

import android.app.Activity;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.animation.Animation;
import com.baidu.mapapi.animation.Transformation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.ewhl.mark.meijialian.volley.BaseVO;
import com.ewhl.mark.meijialian.volley.MyErrorListener;
import com.ewhl.mark.meijialian.volley.MyReponseListener;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 此demo用来展示如何结合定位SDK实现定位，并使用MyLocationOverlay绘制定位位置 同时展示如何使用自定义图标绘制并点击时弹出泡泡
 */
public class ShopMapActivity extends Activity implements SensorEventListener ,ShopAdapter.CollectionListner{

    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    @BindView(R.id.bmapView)
    MapView mMapView;
    @BindView(R.id.return_iv)
    AutoRelativeLayout returnIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.header)
    AutoRelativeLayout header;
    @BindView(R.id.tb_shop)
    TabLayout tabLayout;
    @BindView(R.id.more)
    AutoLinearLayout more;
    @BindView(R.id.lv_shop)
    ListView lvShop;
    @BindView(R.id.ll_shop_list)
    AutoLinearLayout llShopList;
    @BindView(R.id.iv_header)
    CircleImageView ivHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_star)
    ImageView ivStar;
    @BindView(R.id.shop_collection)
    AutoLinearLayout shopCollection;
    @BindView(R.id.tv_classify)
    TextView tvClassify;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_shop_detail)
    AutoLinearLayout llShopDetail;
    @BindView(R.id.rl_info)
    AutoRelativeLayout rlInfo;
    private LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00FF00;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;


    BaiduMap mBaiduMap;
    NetValues netValues;
    // UI相关
    OnCheckedChangeListener radioButtonListener;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    List<ShopBean.ListBean> mapBeans = new ArrayList<ShopBean.ListBean>();
    private float direction;
    LatLng northeast;
    LatLng southwest;
    private Point mScreenCenterPoint;
    private int flag = 1;
    private String scid = "-1";
    ShopAdapter shopAdapter;

    // 初始化全局 bitmap 信息，不用时及时 recycle
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        ButterKnife.bind(this);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mCurrentMode = LocationMode.NORMAL;
        netValues = NetValues.getInstance(this);
        shopAdapter = new ShopAdapter(this);
        shopAdapter.setCollectionListner(this);
        lvShop.setAdapter(shopAdapter);
        TabLayout.Tab tab = tabLayout.newTab();
        tab.setText("全部");
        tab.setTag("-1");
        tabLayout.addTab(tab);

        initdata();


        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                ShopBean.ListBean listBean = (ShopBean.ListBean) marker.getExtraInfo().getSerializable("BEAN");
                netValues.get_shop_info(listBean.getStore_id(), new MyReponseListener() {
                    @Override
                    public void onResponse(BaseVO arg0) {
                        ShopInfo shopInfo=(ShopInfo)arg0;
                        if(shopInfo.getStatus()==200){
                            rlInfo.setVisibility(View.VISIBLE);
                            llShopList.setVisibility(View.GONE);
                            llShopDetail.setVisibility(View.VISIBLE);
                            try {
                                Glide.with(ShopMapActivity.this).load(Uri.parse(shopInfo.getData().getStore_logo())).into(ivHeader);
                                tvName.setText(shopInfo.getData().getStore_name());
                                tvClassify.setText("经营类目："+shopInfo.getData().getBind_class());
                                tvAddress.setText("门店地址："+shopInfo.getData().getProvince()+shopInfo.getData().getCity()+shopInfo.getData().getDistrict()+shopInfo.getData().getStore_address());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, new MyErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        super.onErrorResponse(error);
                    }
                });

                return false;
            }
        });
        List<Marker> markers = mBaiduMap.getMarkersInBounds(mBaiduMap.getMapStatus().bound);
        mLocClient.start();
    }

    private void initdata() {
        netValues.get_near_store_classify(new MyReponseListener() {
            @Override
            public void onResponse(BaseVO arg0) {
                StoreClassify storeClassify = (StoreClassify) arg0;
                if (storeClassify.getList() != null && storeClassify.getList().size() > 0) {
                    for (int i = 0; i < storeClassify.getList().size(); i++) {
                        TabLayout.Tab tab = tabLayout.newTab();
                        tab.setText(storeClassify.getList().get(i).getSc_name());
                        tab.setTag(storeClassify.getList().get(i).getSc_id());
                        tabLayout.addTab(tab);
                    }
                }
            }
        }, new MyErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;

    }

    public void initOverlay(String ne, String sw) {
        // add marker overlay

        netValues.get_near_store_list((String) SPUtils.get(this,"key",""),scid, ne, sw, mCurrentLon, mCurrentLat, new MyReponseListener() {
            @Override
            public void onResponse(BaseVO arg0) {

                try {
                    ShopBean shopBean = (ShopBean) arg0;
                    if (shopBean.getStatus() == 200) {
                        if (mapBeans.size() > 0 && list_equl(mapBeans, shopBean.getList())) {
                            return;
                        }
                        mBaiduMap.clear();
                        mapBeans = shopBean.getList();
                        if(mapBeans.size()==0){
                            llShopList.setVisibility(View.GONE);
                            rlInfo.setVisibility(View.GONE);
                        }else {
                            llShopDetail.setVisibility(View.GONE);
                            rlInfo.setVisibility(View.VISIBLE);
                            llShopList.setVisibility(View.VISIBLE);
                            shopAdapter.setMdata(mapBeans);
                        }
                        for (ShopBean.ListBean bean : mapBeans) {
                            LatLng latLng = new LatLng(bean.getStore_latitude(), bean.getStore_longitude());
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("BEAN", bean);
                            View view = View.inflate(getApplicationContext(), R.layout.item_bean, null);
                            //            TextView tView = (TextView)view.findViewById(R.id.item_bean);
                            //            tView.setText(bean.getId() + "");
                            //将View转化为Bitmap
                            BitmapDescriptor descriptor = BitmapDescriptorFactory.fromView(view);
                            OverlayOptions options = new MarkerOptions().position(latLng).icon(descriptor).extraInfo(bundle).zIndex(9).draggable(true);
                            Marker marker = (Marker) mBaiduMap.addOverlay(options);
                            startTransformation(marker, latLng);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new MyErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
            }
        });


//        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(12.0f);
//        mBaiduMap.setMapStatus(msu);

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    public void startTransformation(Marker markerOptions, LatLng latLng) {
        markerOptions.setAnimation(getTransformation(latLng));
        markerOptions.startAnimation();

    }

    private Animation getTransformation(LatLng llC) {
        Point point = mBaiduMap.getProjection().toScreenLocation(llC);
        LatLng latLng1 = mBaiduMap.getProjection().fromScreenLocation(new Point(point.x, point.y - 100));
        Transformation mTransforma = new Transformation(llC, latLng1, llC);
        mTransforma.setDuration(500);
        mTransforma.setRepeatMode(Animation.RepeatMode.RESTART);//动画重复模式
        mTransforma.setRepeatCount(1);//动画重复次数
        mTransforma.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart() {
            }

            @Override
            public void onAnimationEnd() {

            }

            @Override
            public void onAnimationCancel() {
            }

            @Override
            public void onAnimationRepeat() {

            }
        });

        return mTransforma;
    }

    boolean list_equl(List a, List b) {
        if (a.size() != b.size()) {
            return false;
        }

        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i))) {
                return false;
            }
        }
        return true;
    }

    @OnClick({R.id.return_iv, R.id.more, R.id.shop_collection})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_iv:
                finish();
                break;
            case R.id.more:
                break;
            case R.id.shop_collection:
                break;
        }
    }

    @Override
    public void collected(final int position, int is_shoucang) {
       final List<ShopBean.ListBean> mdata=shopAdapter.getMdata();
        netValues.collection_store(mdata.get(position).getStore_id(), (String) SPUtils.get(this, "key", ""), mdata.get(position).getIs_shoucang(), new MyReponseListener() {
            @Override
            public void onResponse(BaseVO arg0) {
                OptionBean optionBean=(OptionBean) arg0;
                if(optionBean.status==200){
                    if(mdata.get(position).getIs_shoucang()==1){
                        mdata.get(position).setIs_shoucang(0);
                        shopAdapter.setMdata(mdata);
                        shopAdapter.notifyDataSetChanged();
                        Toast.makeText(ShopMapActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();
                    }else {
                        mdata.get(position).setIs_shoucang(1);
                        shopAdapter.setMdata(mdata);
                        shopAdapter.notifyDataSetChanged();
                        Toast.makeText(ShopMapActivity.this, "已收藏", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(ShopMapActivity.this, ""+optionBean.msg, Toast.LENGTH_SHORT).show();
                }
            }
        }, new MyErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
            }
        });
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(16.5f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                northeast = mBaiduMap.getMapStatus().bound.northeast;
                southwest = mBaiduMap.getMapStatus().bound.southwest;
                initOverlay(northeast.longitude + "," + northeast.latitude, southwest.longitude + "," + southwest.latitude);
                tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        scid = (String) tab.getTag();
                        northeast = mBaiduMap.getMapStatus().bound.northeast;
                        southwest = mBaiduMap.getMapStatus().bound.southwest;
                        initOverlay(northeast.longitude + "," + northeast.latitude, southwest.longitude + "," + southwest.latitude);
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {

                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {

                    }
                });

                mBaiduMap.setOnMapRenderCallbadk(new BaiduMap.OnMapRenderCallback() {
                    @Override
                    public void onMapRenderFinished() {


                        northeast = mBaiduMap.getMapStatus().bound.northeast;
                        southwest = mBaiduMap.getMapStatus().bound.southwest;
                        initOverlay(northeast.longitude + "," + northeast.latitude, southwest.longitude + "," + southwest.latitude);

                        Log.d("srgslocation", "ne:" + northeast.latitude + "-----" + northeast.longitude);
                        Log.d("srgslocation", "sw:" + southwest.latitude + "-----" + southwest.longitude);

                    }
                });
            }


        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }


}
